package logic

import (
	"apple/applerpc/applerpc"
	"apple/applerpc/internal/svc"
	"apple/cache"
	"apple/models/mysql"
	"context"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ActivityLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ActivityLogic {
	return &ActivityLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 活动列表
func (l *ActivityLogic) Activity(in *applerpc.ActivityAddRequest) (*applerpc.ActivityAddResponse, error) {
	// todo: add your logic here and delete this line
	var activity []mysql.Activity
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	result, _ := cache.Rdb.Get(l.ctx, "aclist").Result()
	if result == "" {
		mysql.DB.Debug().Limit(int(pageSize)).Offset(int(offset)).Order("class desc").Find(&activity)
		marshal, _ := json.Marshal(&activity)
		cache.Rdb.Set(l.ctx, "aclist", marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &activity)
	}

	var aclist []*applerpc.AcList
	for _, m := range activity {
		list := applerpc.AcList{
			Image:     m.Image,
			Name:      m.Name,
			Publisher: m.Publisher,
			Class:     m.Class,
			Message:   m.Message,
			UserId:    m.UserId,
		}
		aclist = append(aclist, &list)
	}
	return &applerpc.ActivityAddResponse{
		List: aclist,
	}, nil
}
